package org.amos.core.frame.config.mybatis;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.constant.SystemConstant;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Configuration
@EnableTransactionManagement
@MapperScan({SystemConstant.SYS_PACKAGE + ".*.mapper", SystemConstant.SYS_PACKAGE + ".*.modules.*.mapper"})
public class MybatisPlusConfig implements MetaObjectHandler {

    @Autowired(required = false)
    private UserInfoApi userInfoApi;

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        paginationInterceptor.setDbType(DbType.MYSQL);
        //设置请求页大于最大页操作, true 跳回首页;false 继续请,默认为false
        paginationInterceptor.setOverflow(true);
        // 添加分页插件
        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }

    /**
     * 乐观锁插件
     *
     * @return
     */
    @Bean
    public OptimisticLockerInnerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, SystemConstant.CREATE_USER, String.class, getCurrentUser());
        this.strictInsertFill(metaObject, SystemConstant.CREATE_TIME, Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, SystemConstant.UPDATE_USER, String.class, getCurrentUser());
        this.strictUpdateFill(metaObject, SystemConstant.UPDATE_TIME, Date.class, new Date());
    }

    private String getCurrentUser() {
        if (Objects.isNull(userInfoApi)) {
            return StrUtil.EMPTY;
        }
        return userInfoApi.getCurrentUserName();
    }
}
